package fr.insta.reverse.uml.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import fr.insta.reverse.uml.bean.User;
import fr.insta.reverse.uml.routing.Route;
import fr.insta.reverse.uml.service.ServiceFactory;
import fr.insta.reverse.uml.service.ServiceName;
import fr.insta.reverse.uml.service.ServiceUser;

public class ProjectViewFilter implements Filter
{

	@Override
	public void destroy()
	{
	}

	@Override
	public void doFilter(ServletRequest _servletRequest, ServletResponse _servletResponse, FilterChain _filterChain) throws IOException, ServletException
	{
		ServiceUser serviceUser = (ServiceUser) ServiceFactory.getService(ServiceName.ServiceUser);

		HttpServletRequest request = (HttpServletRequest) _servletRequest;

		String route = request.getRequestURI().substring(
				request.getContextPath().length() + 1);

		if (route.contentEquals(Route.ImageDisplay.getRoute()) ||
				route.contentEquals(Route.ProjectView.getRoute()))
		{

			User user = serviceUser.getSessionUser(request);

			boolean isAuthorized = serviceUser.isAuthorizedToView(request.getParameter("idProject"), user);

			System.out.println(isAuthorized);

			if (isAuthorized)
			{
				_filterChain.doFilter(_servletRequest, _servletResponse);
			}
			else
			{
				request.getRequestDispatcher(Route.Error404.getRoute()).forward(_servletRequest, _servletResponse);
			}

			System.out.println("IMAGE !!");
			System.out.println(request.getParameter("idProject"));
		}

		_filterChain.doFilter(_servletRequest, _servletResponse);
	}

	@Override
	public void init(FilterConfig _arg0) throws ServletException
	{
	}

}